<template>
  <div class="course-management">
    <h1>课程管理</h1>
    
    <!-- 添加课程按钮 -->
    <el-button type="primary" @click="showAddDialog">
      <i class="el-icon-plus"></i> 添加课程
    </el-button>

    <!-- 课程列表 -->
    <el-table :data="courses" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="课程ID" width="100"></el-table-column>
      <el-table-column prop="name" label="课程名称" width="200"></el-table-column>
      <el-table-column prop="description" label="课程描述"></el-table-column>
      <el-table-column prop="duration" label="课程时长" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '已发布' ? 'success' : 'info'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="small" type="primary" @click="showProgress(scope.row)">查看进度</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
      <el-form :model="courseForm" :rules="rules" ref="courseForm" label-width="100px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name"></el-input>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input type="textarea" v-model="courseForm.description"></el-input>
        </el-form-item>
        <el-form-item label="课程时长" prop="duration">
          <el-input v-model="courseForm.duration">
            <template #append>分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="courseForm.status">
            <el-option label="草稿" value="草稿"></el-option>
            <el-option label="已发布" value="已发布"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 进度查询对话框 -->
    <el-dialog
      v-model="progressDialogVisible"
      title="课程进度查询"
      width="60%"
      :before-close="() => progressDialogVisible = false"
    >
      <el-table :data="courseProgress" v-loading="!courseProgress.length">
        <el-table-column prop="employeeName" label="员工姓名" width="120" />
        <el-table-column prop="department" label="部门" width="120" />
        <el-table-column prop="progress" label="完成进度" width="200">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.progress"
              :status="scope.row.progress === 100 ? 'success' : ''"
            />
          </template>
        </el-table-column>
        <el-table-column prop="lastStudyTime" label="最近学习时间" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="progressDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加自定义删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      width="30%"
      class="custom-delete-dialog"
      :show-close="false"
    >
      <div class="delete-dialog-content">
        <i class="el-icon-warning warning-icon"></i>
        <p class="delete-message">您确定要删除课程 "{{ courseToDelete?.name }}" 吗？</p>
        <p class="delete-submessage">此操作不可恢复。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { API_BASE_URL } from '@/config/api'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'CourseManagement',
  data() {
    return {
      courses: [
        {
          id: 1,
          name: '前端开发基础',
          description: '学习HTML、CSS和JavaScript的基础知识，掌握现代前端开发技能。',
          duration: '120',
          status: '已发布',
          instructor: '张老师',
          publishDate: '2024-03-15'
        },
        {
          id: 2,
          name: 'Vue.js 实战教程',
          description: '深入学习Vue.js框架，从基础到高级特性的完整课程。',
          duration: '180',
          status: '已发布',
          instructor: '李老师',
          publishDate: '2024-03-14'
        },
        {
          id: 3,
          name: '后端开发入门',
          description: 'Node.js基础教程，包括Express框架和数据库操作。',
          duration: '150',
          status: '草稿',
          instructor: '王老师',
          publishDate: '2024-03-13'
        }
        // ... 可以继续添加更多课程
      ],
      dialogVisible: false,
      dialogTitle: '添加课程',
      courseForm: {
        name: '',
        description: '',
        duration: '',
        status: '草稿'
      },
      progressDialogVisible: false,
      courseProgress: [],
      rules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入课程描述', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入课程时长', trigger: 'blur' },
          { pattern: /^[0-9]+$/, message: '请输入数字', trigger: 'blur' }
        ]
      },
      deleteDialogVisible: false,
      courseToDelete: null,
    }
  },
  methods: {
    // 通用请求方法
    async fetchRequest(url, options = {}) {
      const defaultHeaders = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }

      try {
        const response = await fetch(url, {
          ...options,
          headers: {
            ...defaultHeaders,
            ...options.headers
          }
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const data = await response.json()
        return data
      } catch (error) {
        console.error('请求错误:', error)
        throw error
      }
    },

    // 获取课程列表
    async fetchCourses() {
      try {
        const data = await this.fetchRequest(`${API_BASE_URL}/courses`)
        this.courses = data
      } catch (error) {
        this.$message.error('获取课程列表失败')
      }
    },

    // 修改添加课程方法
    async addCourse(courseData) {
      try {
        // 发送后端请求
        const response = await this.fetchRequest(`${API_BASE_URL}/courses`, {
          method: 'POST',
          body: JSON.stringify({
            name: courseData.name,
            description: courseData.description,
            duration: courseData.duration,
            status: courseData.status
          })
        })
        
        // 使用后端返回的数据更新前端
        const newCourse = response.data
        this.courses.push(newCourse)
        this.updateLocalStorage()
        
        return newCourse
      } catch (error) {
        this.$message.error('添加课程失败')
        throw error
      }
    },

    // 添加生成新ID的方法
    generateNewId() {
      const maxId = Math.max(...this.courses.map(course => course.id), 0)
      return maxId + 1
    },

    // 添加本地存储更新方法
    updateLocalStorage() {
      localStorage.setItem('courses', JSON.stringify(this.courses))
    },

    // 修改删除课程方法
    async deleteCourse(id) {
      try {
        await this.fetchRequest(`${API_BASE_URL}/courses/${id}`, {
          method: 'DELETE'
        })
        const index = this.courses.findIndex(item => item.id === id)
        this.courses.splice(index, 1)
        this.updateLocalStorage()
      } catch (error) {
        this.$message.error('删除课程失败')
        throw error
      }
    },

    // 提交表单处理
    async submitForm() {
      this.$refs.courseForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogTitle === '添加课程') {
              await this.addCourse(this.courseForm)
              this.$message.success('添加课程成功')
            } else if (this.dialogTitle === '编辑课程') {
              const index = this.courses.findIndex(course => course.id === this.courseForm.id)
              if (index !== -1) {
                this.courses[index] = { ...this.courseForm }
                this.updateLocalStorage()
                this.dialogVisible = false
                alert('课程编辑成功！')
              } else {
                alert('课程未找到！')
              }
            }
            this.dialogVisible = false
          } catch (error) {
            console.error(error)
            alert('操作失败，请稍后重试')
          }
        }
      })
    },

    // 删除课程处理
    handleDelete(row) {
      this.courseToDelete = row;
      this.deleteDialogVisible = true;
    },

    // 修改确认删除方法
    async confirmDelete() {
      try {
        const index = this.courses.findIndex(item => item.id === this.courseToDelete.id);
        if (index > -1) {
          this.courses.splice(index, 1);
          this.updateLocalStorage();
          this.deleteDialogVisible = false;
          this.$message.success('删除成功');
        }
        this.courseToDelete = null;
      } catch (error) {
        this.$message.error('删除失败');
      }
    },

    showAddDialog() {
      this.dialogTitle = '添加课程'
      this.courseForm = {
        name: '',
        description: '',
        duration: '',
        status: '草稿'
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑课程'
      this.courseForm = { ...row }
      this.dialogVisible = true
    },

    // 查看进度
    async showProgress(course) {
      try {
        // 模拟后端数据
        const mockData = [
          {
            employeeName: "张三",
            department: "技术部",
            progress: 85,
            lastStudyTime: "2024-03-20T14:30:00"
          },
          {
            employeeName: "李四",
            department: "市场部",
            progress: 100,
            lastStudyTime: "2024-03-19T16:45:00"
          },
          {
            employeeName: "王五",
            department: "人事部",
            progress: 30,
            lastStudyTime: "2024-03-21T09:15:00"
          },
          {
            employeeName: "赵六",
            department: "技术部",
            progress: 60,
            lastStudyTime: "2024-03-20T11:20:00"
          }
        ];

        // 使用模拟数据替代 API 调用
        // const data = await this.fetchRequest(`${API_BASE_URL}/courses/${course.id}/progress`, {
        //   method: 'GET'
        // })
        
        this.courseProgress = mockData.map(item => ({
          employeeName: item.employeeName || '未知',
          department: item.department || '未知',
          progress: parseInt(item.progress) || 0,
          lastStudyTime: this.formatDateTime(item.lastStudyTime)
        }));
        
        this.progressDialogVisible = true;
      } catch (error) {
        this.$message.error('获取课程进度失败：' + error.message);
        console.error('获取课程进度失败:', error);
      }
    },

    // 加日期格式化方法
    formatDateTime(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  },
  // 组件创建时获取课程列表
  created() {
    this.fetchCourses()
  }
}
</script>

<style scoped>
.course-management {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
  display: block;
}

.el-button {
  margin-left: 10px;
}

/* 修改嵌套的 CSS 样式写法 */
.custom-delete-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.custom-delete-dialog :deep(.el-dialog__header) {
  display: none;
}

.custom-delete-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #DCDFE6;
  padding: 15px 20px;
}

.custom-delete-dialog {
  background: rgba(255, 255, 255, 0.95) !important;
}

.delete-dialog-content {
  text-align: center;
  padding: 20px 0;
}

.warning-icon {
  font-size: 48px;
  color: #E6A23C;
  margin-bottom: 15px;
}

.delete-message {
  font-size: 16px;
  color: #303133;
  margin-bottom: 10px;
}

.delete-submessage {
  font-size: 14px;
  color: #909399;
}
</style>